package com.reebake.ideal.json.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Json工具， 接口参照hutool的JsonUtil
 */
public class JsonUtil implements ApplicationContextAware {

    private static ObjectMapper objectMapper;

    @SneakyThrows
    public static <T> T toBean(String jsonString, Class<T> beanClass) {
        if(StrUtil.isBlank(jsonString)) {
            return null;
        }
        return objectMapper.readValue(jsonString, beanClass);
    }

    @SneakyThrows
    public static <T> T toBean(byte[] jsonBytes, Class<T> beanClass) {
        if(ArrayUtil.isEmpty(jsonBytes)) {
            return null;
        }
        return objectMapper.readValue(jsonBytes, beanClass);
    }

    @SneakyThrows
    public static <T> T toBean(String jsonString, TypeReference<T> beanClass) {
        if(StrUtil.isBlank(jsonString)) {
            return null;
        }
        return objectMapper.readValue(jsonString, beanClass);
    }

    @SneakyThrows
    public static String toJsonStr(Object obj) {
        if (ObjectUtil.isNull(obj)) {
            return null;
        }
        return objectMapper.writeValueAsString(obj);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        JsonUtil.objectMapper = applicationContext.getBean(ObjectMapper.class);
    }
}
